//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package issue_dao

import (
	"context"

	"atomgit.com/openlinksaas-org/api-server/dao/db_ns"
	"atomgit.com/openlinksaas-org/proto-gen-go.git/project_sprit_api"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
)

type SpritInfoDbItem struct {
	SpritId      string `bson:"_id"`
	ProjectId    string `bson:"projectId"`
	SummaryState uint32 `bson:"summaryState"`
}

func (item *SpritInfoDbItem) ToSpritInfo(taskCount, bugCount uint32) *project_sprit_api.SpritInfo {
	return &project_sprit_api.SpritInfo{
		SpritId:      item.SpritId,
		ProjectId:    item.ProjectId,
		TaskCount:    taskCount,
		BugCount:     bugCount,
		SummaryState: project_sprit_api.SUMMARY_STATE(item.SummaryState),
	}
}

type _SpritDao struct {
	mc *mongo.Collection
}

func newSpritDao(db *mongo.Database) (*_SpritDao, error) {
	mc := db.Collection(db_ns.DB_NS_ISSUE + "sprit")
	return &_SpritDao{mc: mc}, nil
}

func (db *_SpritDao) Insert(ctx context.Context, dbItem *SpritInfoDbItem) error {
	_, err := db.mc.InsertOne(ctx, dbItem)
	return err
}

func (db *_SpritDao) Get(ctx context.Context, projectId, spritId string) (*SpritInfoDbItem, error) {
	retItem := &SpritInfoDbItem{}
	err := db.mc.FindOne(ctx, bson.M{"_id": spritId, "projectId": projectId}).Decode(retItem)
	return retItem, err
}

func (db *_SpritDao) Exist(ctx context.Context, projectId, spritId string) (bool, error) {
	count, err := db.mc.CountDocuments(ctx, bson.M{"_id": spritId, "projectId": projectId})
	return count > 0, err
}

func (db *_SpritDao) Remove(ctx context.Context, projectId, spritId string) error {
	_, err := db.mc.DeleteOne(ctx, bson.M{"_id": spritId, "projectId": projectId})
	return err
}

func (db *_SpritDao) UpdateSummaryState(ctx context.Context, projectId, spritId string, summaryState uint32) error {
	_, err := db.mc.UpdateOne(ctx, bson.M{"_id": spritId, "projectId": projectId},
		bson.M{"$set": bson.M{"summaryState": summaryState}})
	return err
}
